import Cookies from "js-cookie";
import { ElMessage } from 'element-plus'
import { allRoutes } from "./routes";
import { RouteRecordRaw } from "vue-router";
import { userStore } from "@/store/user";
// 获取并存储动态路由到仓库

export const getAddRoute = (role: string) => {
  // 判断是否登录
  if (!Cookies.get("token")) {
    ElMessage.error("请登录！")
  }
  // 无权限时，添加判断
  // 添加动态路由
  const res = setAddRoute(role)
  // 返回权限路由
  return res
}
// 添加动态路由
export const setAddRoute = (role: string) => {
  let newArr: any = []
  newArr.push({
    path: allRoutes[0].path,
    redirect: allRoutes[0].redirect,
    component: allRoutes[0].component,
    children: []
  })
  // 生成权限路由
  const res = filterAddRoute(allRoutes[0].children, role)
  res.forEach(item => newArr[0].children.push(item))
  userStore().setacheList(newArr[0])
  return newArr[0]
}
// 根据权限过滤该用户的权限路由
export const filterAddRoute = (arr: any, role: string) => {
  const newArr: Array<RouteRecordRaw> = []
  arr.forEach((item: any) => {
    const temp = { ...item }
    if (item.meta) {
      const flag = item.meta.roles.findIndex((el: string) => el === role)
      if (flag !== -1) {
        if (item.children) {
          temp.children = filterAddRoute(item.children, role)
        }
        newArr.push(temp)
      }
    }
  })
  return newArr
}
// 扁平化路由数组
export const flatAddRoute = (arr: Array<RouteRecordRaw>) => {
  if (arr.length === 0) {
    ElMessage.error("没有可获取的路由")
  }
  arr.forEach((item: RouteRecordRaw, i) => {
    if (item.children) {

    }
  })
}